package ltd.bugs.tool.signature.factory.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Map;

import ltd.bugs.tool.signature.attribute.SignatureAttribute;
import ltd.bugs.tool.signature.factory.Signature;
import ltd.bugs.tool.signature.utils.ExtraUtils;
import ltd.bugs.tool.signature.utils.StringUtils;

/**
 * @author zhengzhq
 * @Title: PersonalGeneralSignature
 * @Description: 以xxx印结束的格式来呈现印章
 * @date 018/8/9下午5:30
 */
public class PersonalSuffixSignature implements Signature {

  private static Logger logger = LoggerFactory.getLogger(PersonalSuffixSignature.class);

  public BufferedImage draw(Font font, Color color, int width, int height,
                            Map<String, Object> extras) {
    String name = ExtraUtils.getAttributeValue(extras, SignatureAttribute.SIGNATURE_TEXT,
            String.class);
    if (StringUtils.isEmpty(name)) {
      throw new IllegalArgumentException("name can't be empty!");
    }

    if (height < font.getSize() * 2) {
      throw new IllegalArgumentException("invalid height! height shoud not less than " +
              font.getSize() * 2);
    }
    int nameOffset = ExtraUtils.getAttributeValue(extras, SignatureAttribute.NAME_OFFSET,
            Integer.class, 10);
    char[] nameChars = name.toCharArray();

    int mod = nameChars.length % 2;
    int minWidth = (nameChars.length / 2 + (mod != 0 ? 1 : 0)) * font.getSize();
    if (width < minWidth) {
      throw new IllegalArgumentException("invalid width! width should not be less than " +
              minWidth);
    }
    int borderWidth = ExtraUtils.getAttributeValue(extras, SignatureAttribute.BORDER_WIDTH,
            Integer.class, 5);

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = image.createGraphics();
    // 设置画笔颜色
    g2d.setColor(color);
    // 设置字体
    font = new Font(font.getFontName(), Font.LAYOUT_LEFT_TO_RIGHT, font.getSize());
    g2d.setFont(font);
    Stroke stroke = g2d.getStroke();

    // 画边框
    g2d.setStroke(new BasicStroke(borderWidth));
    g2d.drawRect(0, 0, width, height);

    g2d.setStroke(stroke);
    // 两个字一列进行展示
    int column = nameChars.length / 2 + (nameChars.length % 2 == 1 ? 1 : 0);
    int widthOffset = (width - column * font.getSize()) / 2;
    int heightOffset = (height - 2 * font.getSize()) / 2;
    if (logger.isDebugEnabled()) {
      logger.debug("width offset: {}, height offset: {}", widthOffset, heightOffset);
    }

    for (int i = 0; i < nameChars.length; i++) {
      boolean isNewColumn = i % 2 == 0;
      g2d.drawString(new String(new char[]{nameChars[i]}),
              width - widthOffset - (i / 2 + 1) * font.getSize(),
              height - heightOffset - (isNewColumn ? 1 : 0) * font.getSize());
    }

    return image;
  }
}
